package com.linrung.sf.scheduler.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.linrung.core.utils.SpringPropertyUtils;
import org.apache.log4j.Logger;

import java.util.Map;

/**
 * 调用河源12345短信接口发送短信
 */
public class SendMessageBy12345Util {

    private static final Logger LOGGER = Logger.getLogger(SendMessageBy12345Util.class);

    private static final String publicKeyBase64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTY2/i+i/JW0YWvXPyouOAFo7fqbCTP3fObgXvkGb5cWdZWjzY/l6bo/xWNdxhNlyooG2dcCBfCrcDtNilfZBkqgOHpb+2QdvC3grd5z7UL6n2a6/wK9lCCUW3TymIW1aXosi1S3NJM13PSSsg8nGLekBeiYM0m2fIahaDwRuRrQIDAQAB";

    private static final ThreadLocal<RSA> rsa = ThreadLocal.withInitial(() -> SecureUtil.rsa(null, publicKeyBase64));

    private static String SMS_API = null;

    private static final String SYS_CODE = "HYYZYOA";

    /**
     * 发送短信
     * @param smsContent 短信内容
     * @param mobiles 手机号码数组
     */
    public static void sendMessage(final String smsContent, final String...mobiles) {
        if (StrUtil.isBlank(smsContent) || CollUtil.size(mobiles) == 0) {
            return;
        }
        ThreadUtil.execAsync(() -> send(smsContent, ArrayUtil.join(mobiles, StrPool.COMMA)));
    }

    private static void send(String smsContent, String mobiles) {
        try {
            if (null == SMS_API) {
                SMS_API = SpringPropertyUtils.getPropertyValue("HY12345_SMS_API");
            }
            JSONObject params = new JSONObject();
            params.putOpt("mobiles", mobiles);
            params.putOpt("content", smsContent);
            params.putOpt("sys", SYS_CODE);
            Map<String, Object> paramMap = MapUtil.newHashMap();
            paramMap.put("smsBody", encryptBase64(params.toString()));
            String result= HttpUtil.post(SMS_API, paramMap, 10000);
            if (!JSONUtil.isJsonObj(result)) {
                LOGGER.error("[12345短信接口] 返回值无法识别：" + result);
                return;
            }
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if (!jsonObject.getBool("success", false)) {
                LOGGER.error("[12345短信接口] 发送短信失败：" + result);
            }
        } catch (Exception ex) {
            LOGGER.error("[12345短信接口] 调用接口时异常", ex);
        }
    }

    public static String encryptBase64(String str) {
        try {
            if (StrUtil.isBlank(str)) {
                throw new RuntimeException("加密字符串不能为空");
            }
            return rsa.get().encryptBase64(str, CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);
        } finally {
            rsa.remove();
        }
    }

}
